package com.ft.admix;

import com.ft.admix.base.BaseAd;
import com.ft.admix.common.AdType;
import com.ft.admix.config.AdClassConfig;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AdFactory {
    private static final Map<String, AdClassConfig> platformConfigs = new ConcurrentHashMap<>();

    // 注册平台配置
    public static void registerPlatform(AdClassConfig config) {
        platformConfigs.put(config.getPlatformName().toUpperCase(), config);
    }

    // 创建广告实例
    public static BaseAd createAd(String platformName, AdType adType) {
        AdClassConfig config = platformConfigs.get(platformName.toUpperCase());
        if (config == null) {
            throw new IllegalArgumentException("Platform not registered: " + platformName);
        }

        String className = config.getAdClassMap().get(adType.name());
        if (className == null) {
            throw new IllegalArgumentException(
                    String.format("Ad type %s not supported for platform %s", adType, platformName)
            );
        }

        try {
            Class<?> clazz = Class.forName(className);
            return (BaseAd) clazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create ad instance", e);
        }
    }

    // 获取平台初始化器
    public static Object createPlatformInitializer(String platformName) {
        AdClassConfig config = platformConfigs.get(platformName.toUpperCase());
        if (config == null || config.getInitializerClass() == null) {
            return null;
        }

        try {
            Class<?> clazz = Class.forName(config.getInitializerClass());
            return clazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create platform initializer", e);
        }
    }
}